import React, { useEffect, Fragment, useState } from 'react';
import { connect } from 'umi';
import { Form, Button, Table, Card, Input, DatePicker, Select } from 'antd';
import groupBy from 'lodash/groupBy';
import classNames from 'classnames';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AdvancedSearch from '@/components/AdvancedSearch';
import TableFilter from '@/components/TableFilter';
import { withRoutePage } from '@/utils/enhanceUtils';
import { download } from '@/utils/utils';
import { extractDataList, getCountryMailCnList, getNum } from '@/services/setting/mailSubscribe';
import { dictionaryList } from '@/services/dictionary';
import routerReplace from '@/utils/routerReplace';
import moment from 'moment';
import Pagination from '@/components/Pagination';
import styles from './MailSubscribe.less';

const { RangePicker } = DatePicker;
const MailList = ({ form, dispatch, loading, mailSubscribe, ...rags }) => {
    const { getFieldDecorator } = form;
    const { pagination, mailList } = mailSubscribe;
    // 基础字典数据
    const [mailDictList, setMailDictList] = useState({ subscribeFlag: [], unsubscribeReason: [] });
    // 地区列表数据
    const [countryList, setCountryList] = useState([]);
    const [cancelNum, setCancelNum] = useState('');
    const [subscribeNum, setSubscribeNum] = useState('');
    const [orderByField, setOrderByField] = useState('');
    const [subscribeFlag, setSubscribeFlag] = useState('');
    const [unsubscribeReason, setUnsubscribeReason] = useState('');
    const [sortedInfo, setSortedInfo] = useState({});
    const [filteredInfo, setFilteredInfo] = useState({});

    const getPayload = pageNo => {
        const { subscribeTime = ['', ''], unsubscribeTime = ['', ''], ...params } = form.getFieldsValue();
        const payload = {
            ...params,
            scribeStartTime: subscribeTime[0] && subscribeTime[0].format('YYYY-MM-DD HH:mm:ss'),
            scribeEndTime: subscribeTime[1] && subscribeTime[1].format('YYYY-MM-DD HH:mm:ss'),
            cancelStartTime: unsubscribeTime[0] && unsubscribeTime[0].format('YYYY-MM-DD HH:mm:ss'),
            cancelEndTime: unsubscribeTime[1] && unsubscribeTime[1].format('YYYY-MM-DD HH:mm:ss'),
            orderByField,
            subscribeFlag,
            unsubscribeReason,
            pageNo: pageNo || pagination.current,
            pageSize: pagination.pageSize
        };
        return payload;
    };
    const getMailNum = async () => {
        const res = await getNum();
        if (res.code === 10000) {
            setCancelNum(res.data.cancelNum);
            setSubscribeNum(res.data.subscribeNum);
        }
    };
    const fetchMailList = (ctx = {}) => {
        getMailNum();
        const { pageNo = null } = ctx;
        routerReplace({ query: getPayload(pageNo) });
        dispatch({
            type: 'mailSubscribe/fetchMailList',
            payload: getPayload(pageNo)
        });
    };
    const getFilteredList = arr =>
        arr.map(item => {
            let text = item.dictName;
            if (item.dictValue === 'subscribe_no') {
                text = '已退订';
            } else if (item.dictValue === 'subscribe_yes') {
                text = '已订阅';
            }
            return {
                value: item.dictValue,
                text
            };
        });

    const tableColumns = [
        {
            title: '收件邮箱',
            dataIndex: 'email',
            isSearchable: true,
            width: '20%',
            searchTitle: '邮箱',
            type: 'input'
        },
        {
            title: '订阅地区',
            width: '10%',
            dataIndex: 'countryCodeName',
            isSearchable: true,
            type: 'select',
            searchDataIndex: 'countryCode'
        },
        {
            title: '订阅时间',
            dataIndex: 'subscribeTime',
            width: '15%',
            sorter: true,
            sortOrder: sortedInfo.columnKey === 'subscribeTime' && sortedInfo.order,
            isSearchable: true,
            type: 'timeRange'
        },
        {
            title: '订阅状态',
            dataIndex: 'subscribeFlag',
            width: 120,
            filters: getFilteredList(mailDictList.subscribeFlag),
            filteredValue: filteredInfo.subscribeFlag || null,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            filterMultiple: false,
            render: (text, record) => {
                if (record.subscribeFlag === 'subscribe_yes') {
                    return (
                        <span className={styles['subscribe-status']}>
                            <span className={classNames(styles['round-dot'], styles.green)}></span>
                            已订阅
                        </span>
                    );
                }
                if (record.subscribeFlag === 'subscribe_no') {
                    return (
                        <span className={styles['subscribe-status']}>
                            <span className={classNames(styles['round-dot'], styles.gray)}></span>
                            已退订
                        </span>
                    );
                }
                return <span>一一</span>;
            }
        },
        {
            title: '退订时间',
            dataIndex: 'unsubscribeTime',
            width: '15%',
            isSearchable: true,
            type: 'timeRange',
            sorter: true,
            sortOrder: sortedInfo.columnKey === 'unsubscribeTime' && sortedInfo.order,
            render: text => <span>{text || '一一'}</span>
        },
        {
            title: '退订原因',
            dataIndex: 'unsubscribeReason',
            filteredValue: filteredInfo.unsubscribeReason || null,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            filterMultiple: false,
            filters: getFilteredList(mailDictList.unsubscribeReason.filter(i => i.remark === 'cn')),
            render: (text, record) => (
                <div
                    className={styles['unsubscribe-reason']}
                    // eslint-disable-next-line react/no-danger
                    dangerouslySetInnerHTML={{ __html: record.unsubscribeReasonName || '一一' }}
                    text={record.unsubscribeReasonName}
                />
            )
        }
    ];
    const updateOrderByField = sorter => {
        let newOrderBy = null;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'subscribeTime') {
                sorterField = 'subscribe_time';
            }
            if (sorter.field === 'unsubscribeTime') {
                sorterField = 'unsubscribe_time';
            }
            const order = sorter.order && sorter.order.trim().split('end')[0];
            newOrderBy = `${sorterField} ${order}`;
        }
        setOrderByField(newOrderBy || '');
    };
    // 表格表头点击切换排序
    const changeTable = async (paginations, filters = {}, sorter = {}) => {
        const extra = {};
        if (filteredInfo !== filters) {
            extra.current = 1;
            setFilteredInfo(filters);
        }
        if (sortedInfo !== sorter) {
            extra.current = 1;
            setSortedInfo(sorter);
        }
        updateOrderByField(sorter);
        setUnsubscribeReason(filters.unsubscribeReason ? filters.unsubscribeReason.join() : '');
        setSubscribeFlag(filters.subscribeFlag ? filters.subscribeFlag.join() : '');
        dispatch({
            type: 'mailSubscribe/save',
            payload: {
                pagination: {
                    ...pagination,
                    ...paginations,
                    ...extra
                }
            }
        });
    };

    const onSearch = () => {
        fetchMailList({ pageNo: 1 });
    };

    const downloadMailList = async () => {
        const { pageNo, pageSize, ...otherParams } = getPayload();
        download({
            getData: () => extractDataList(otherParams)
        });
    };

    const getDict = async () => {
        const res = await dictionaryList({ codes: ['subscribeFlag', 'unsubscribeReason'] });
        if (res.code === 10000) {
            setMailDictList(groupBy(res.data, 'code'));
        }
    };
    const getCountryList = async () => {
        const res = await getCountryMailCnList({ countryName: '' });
        if (res.code === 10000) {
            setCountryList(res.data);
        }
    };
    const filterOption = (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    const handleSubmit = () => {
        onSearch();
    };
    useEffect(() => {
        getDict();
        getCountryList();
        return () => {
            dispatch({
                type: 'mailSubscribe/save',
                payload: {
                    mailList: [],
                    pagination: {
                        pageSize: 10,
                        current: 1,
                        total: 0
                    }
                }
            });
        };
    }, []);

    useEffect(() => {
        const {
            location: { query }
        } = rags;
        const { cancelStartTime, cancelEndTime, scribeEndTime, scribeStartTime, ...otherQuery } = query;
        form.setFieldsValue(otherQuery);
        if (cancelStartTime && cancelEndTime) {
            form.setFieldsValue({
                unsubscribeTime: [moment(cancelStartTime), moment(cancelEndTime)]
            });
        }
        if (scribeStartTime && scribeEndTime) {
            form.setFieldsValue({
                subscribeTime: [moment(scribeStartTime), moment(scribeEndTime)]
            });
        }
        fetchMailList();
    }, [pagination.pageSize, pagination.current, orderByField, subscribeFlag, unsubscribeReason]);
    const extraBtn = (
        <Button onClick={downloadMailList} className="extract-btn">
            导出
        </Button>
    );
    return (
        <PageHeaderWrapper>
            <Card
                bordered={false}
                title={
                    <Fragment>
                        <span className={styles.title}>邮箱订阅</span>
                        <div className={styles.counts}>
                            (<span>订阅邮箱数：{subscribeNum}</span>
                            <em>|</em>
                            <span>退订邮箱数：{cancelNum}</span>)
                        </div>
                    </Fragment>
                }
            >
                <AdvancedSearch form={form} onSubmit={handleSubmit} onReset={handleSubmit} extraButtons={extraBtn}>
                    {tableColumns
                        .filter(targetColumn => targetColumn.isSearchable)
                        .map(column => {
                            if (column.type === 'input') {
                                return (
                                    <Form.Item label={column.searchTitle || column.title} key={column.dataIndex}>
                                        {getFieldDecorator(
                                            column.searchDataIndex || column.dataIndex,
                                            {}
                                        )(
                                            <Input
                                                placeholder={`请输入${column.searchTitle || column.title}`}
                                                allowClear
                                            />
                                        )}
                                    </Form.Item>
                                );
                            }
                            if (column.type === 'select') {
                                return (
                                    <Form.Item label={column.searchTitle || column.title} key={column.dataIndex}>
                                        {getFieldDecorator(
                                            column.searchDataIndex || column.dataIndex,
                                            {}
                                        )(
                                            <Select
                                                showSearch
                                                allowClear
                                                filterOption={filterOption}
                                                getPopupContainer={trigger => trigger.parentNode}
                                                placeholder={`请选择${column.searchTitle || column.title}`}
                                                style={{ width: '100%' }}
                                            >
                                                {countryList.map(item => (
                                                    <Select.Option value={item.value} key={item.value}>
                                                        {item.name}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )}
                                    </Form.Item>
                                );
                            }
                            if (column.type === 'timeRange') {
                                return (
                                    <Form.Item label={column.searchTitle || column.title} key={column.dataIndex}>
                                        {getFieldDecorator(
                                            column.searchDataIndex || column.dataIndex,
                                            {}
                                        )(
                                            <RangePicker
                                                showTime={{
                                                    hideDisabledOptions: true
                                                }}
                                                getCalendarContainer={trigger => trigger.parentNode}
                                                format="YYYY-MM-DD HH:mm:ss"
                                            />
                                        )}
                                    </Form.Item>
                                );
                            }
                            return null;
                        })}
                </AdvancedSearch>
                {/* <div style={{ marginBottom: '20px' }}>
                    <Form layout="inline" onSubmit={handleSubmit}>
                        {tableColumns
                            .filter(targetColumn => targetColumn.isSearchable)
                            .map(column => {
                                if (column.type === 'input') {
                                    return (
                                        <Form.Item label={column.searchTitle || column.title} key={column.dataIndex}>
                                            {getFieldDecorator(
                                                column.searchDataIndex || column.dataIndex,
                                                {}
                                            )(<Input placeholder={`请输入${column.searchTitle || column.title}`} />)}
                                        </Form.Item>
                                    );
                                }
                                if (column.type === 'select') {
                                    return (
                                        <Form.Item label={column.searchTitle || column.title} key={column.dataIndex}>
                                            {getFieldDecorator(
                                                column.searchDataIndex || column.dataIndex,
                                                {}
                                            )(
                                                <Select
                                                    showSearch
                                                    allowClear
                                                    filterOption={filterOption}
                                                    placeholder={`请选择${column.searchTitle || column.title}`}
                                                    style={{ width: '200px' }}
                                                >
                                                    {countryList.map(item => (
                                                        <Select.Option value={item.value} key={item.value}>
                                                            {item.name}
                                                        </Select.Option>
                                                    ))}
                                                </Select>
                                            )}
                                        </Form.Item>
                                    );
                                }
                                if (column.type === 'timeRange') {
                                    return (
                                        <Form.Item label={column.searchTitle || column.title} key={column.dataIndex}>
                                            {getFieldDecorator(
                                                column.searchDataIndex || column.dataIndex,
                                                {}
                                            )(
                                                <RangePicker
                                                    showTime={{
                                                        hideDisabledOptions: true
                                                    }}
                                                    format="YYYY-MM-DD HH:mm:ss"
                                                />
                                            )}
                                        </Form.Item>
                                    );
                                }
                                return null;
                            })}
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button
                                onClick={() => {
                                    form.resetFields();
                                    setSortedInfo({});
                                    setFilteredInfo({});
                                    fetchMailList();
                                }}
                            >
                                重置
                            </Button>
                        </Form.Item>
                        <Form.Item style={{ float: 'right', marginRight: '0', zIndex: 999, marginBottom: '20px' }}>
                            <Button onClick={downloadMailList} className="extract-btn">
                                导出
                            </Button>
                        </Form.Item>
                    </Form>
                </div> */}
                <Table
                    loading={loading}
                    dataSource={mailList}
                    columns={tableColumns}
                    onChange={changeTable}
                    rowKey="id"
                    pagination={false}
                />
                <Pagination
                    {...pagination}
                    onChange={changeTable}
                    sorter={sortedInfo}
                    filters={filteredInfo}
                    loading={loading}
                />
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ loading, mailSubscribe }) => ({
        mailSubscribe,
        loading: loading.models.mailSubscribe
    }))(Form.create()(MailList))
);
